import {createRouter, createWebHistory} from 'vue-router';

import HomeView from '@/views/HomeView.vue';

const options = {
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
      {
        path: '',
        name: 'root',
        component: HomeView,
        meta: { title: '首页' }
      },
      {
        path: '/home',
        name: 'home',
        component: HomeView,
        beforeEnter(to, from) {
          console.log( 'home beforeEnter - from:', from );
          console.log( 'home beforeEnter - to:', to );
        },
        meta: { title: '主页' }
      },
      {
        path: '/basic',
        name: 'basic',
        component: () => {
          console.log( '解析异步路由组件' );
          return import('@/views/BasicView.vue');
        },
        // 路由独享的守卫
        beforeEnter(to, from) {
          console.log( `路由独享守卫(basic beforeEnter): 从${from.path}到${to.path}` );
        },
        meta: { title: '基础' }
      },
      {
        path: '/user/:id',
        name: 'user',
        component: () => import('@/views/UserView.vue') ,
        meta: { title: '用户' }
      }
    ]
}

const router = createRouter( options );

// 全局前置守卫
router.beforeEach( (to,from) => {
  console.log( 'beforeEach - from:', from );
  console.log( 'beforeEach - to:', to );
} );

// 全局解析守卫
router.beforeResolve( (to,from) => {
  console.log( 'beforeResolve - from:', from );
  console.log( 'beforeResolve - to:', to );
});

const hook = (to, from) => {
  console.log( 'afterEach - from:', from );
  console.log( 'afterEach - to:', to );
  if( document.title != to.meta.title ) {
    console.log( '修改标题' );
    // 将路由元信息中的title作为页面标题来使用
    document.title = to.meta.title;
  }
}

// 全局后置钩子
router.afterEach( hook );

export default router;